<template>
  <a-tree-select
    :data="tree"
    v-model="copyValue"
    :disabled="disabled"
    :placeholder="placeholder"
    :fieldNames="{
      key: 'id',
      title: 'name',
    }"
  />
</template>

<script setup lang="ts">
  import { ref, computed } from 'vue';
  import { GetOrganizationchart } from '@/api/home/System settings/organizational-structure/index';

  const props = withDefaults(
    // 参数说明
    defineProps<{
      placeholder?: string;
      value?: number;
      disabled?: boolean;
    }>(),
    {
      placeholder: '请选择部门',
      disabled: false,
    }
  );
  let emit = defineEmits(['update:value']);
  let copyValue = computed({
    get: () => {
      return props.value;
    },
    set: (val) => {
      emit('update:value', val);
    },
  });

  let tree = ref<any[]>([]);

  let loadTree = (id: any, list: any[]): any[] => {
    return (
      list
        .filter((item) => item.pid === id)
        .map((item: any) => {
          return {
            ...item,
            children: loadTree(item.id, list),
          };
        }) || []
    );
  };

  let loadDate = async () => {
    let res = await GetOrganizationchart();
    let findItem = res.department?.find((item: any) => !item.pid);
    tree.value = findItem
      ? [{ ...findItem, children: loadTree(findItem.id, res.department) }]
      : [];
  };

  loadDate();
</script>

<style scoped></style>
